﻿using MESMian.Common;
using MESMian.Context;
using MESMian.Test;
using Microsoft.EntityFrameworkCore;
using Model;
using Org.BouncyCastle.Pqc.Crypto.Frodo;
using System.Data;
using System.Runtime.CompilerServices;

namespace MESMian.Forms.ProductionCategory
{
    public partial class ProductionCategoryList : ListBase
    {
        public ProductionCategoryList()
        {
            InitializeComponent();
            Text = "产品类型";
            Load += ProductionCategoryList_Load;
        }

        private void ProductionCategoryList_Load(object? sender, EventArgs e)
        {
            ucPager1.GetPagerData();
        }

        public override int BindDataGridView()
        {
            int totalCount = 0;
            using (var mtx = new MyContext())
            {
                var query = from p in mtx.ProductCategories
                            join u1 in mtx.Users on p.CreateUserId equals u1.UserId
                            into result1
                            from item1 in result1.DefaultIfEmpty() // 左连接，处理 CreateUserId 为空的情况
                            join u2 in mtx.Users on p.LastUpdateUserId equals u2.UserId
                            into result2
                            from item2 in result2.DefaultIfEmpty() // 左连接，处理 LastUpdateUserId 为空的情况
                            select new
                            {
                                p.ProductCategoryId,
                                p.ProductCategoryName,
                                p.Status,
                                StatusText = p.Status == 0 ? "正常" : "禁用",
                                p.CreateUserId,
                                CreateUserName = item1 != null ? item1.UserName : null, // 如果没有匹配的用户，返回 null
                                p.CreateTime,
                                p.LastUpdateUserId,
                                LastUpdateUserName = item2 != null ? item2.UserName : null, // 如果没有匹配的用户，返回 null
                                p.LastUpdateTime
                            };

                if (!string.IsNullOrWhiteSpace(txtProductCategories.Text))
                    query = query.Where(p => p.ProductCategoryName.Contains(txtProductCategories.Text));

                if (cbbStatus.SelectedIndex != -1 && cbbStatus.SelectedIndex != 0)
                {
                    if (cbbStatus.SelectedValue != null)
                    {
                        var status = (int)cbbStatus.SelectedValue;
                        query = query.Where(p => p.Status == status);
                    }
                }

                if (!string.IsNullOrWhiteSpace(dtpCreateTimeStart.Text))
                {
                    DateTime createTimeStart = DateTime.Parse(dtpCreateTimeStart.Text + " 00:00:00");
                    query = query.Where(p => p.CreateTime >= createTimeStart);
                }

                if (!string.IsNullOrWhiteSpace(dtpCreateTimeEnd.Text))
                {
                    DateTime createTimeEnd = DateTime.Parse(dtpCreateTimeEnd.Text + " 23:59:59");
                    query = query.Where(p => p.CreateTime <= createTimeEnd);
                }

                totalCount = query.Count();

                query = query.OrderByDescending(p => p.ProductCategoryId).Skip((ucPager1.CurrentPage - 1) * ucPager1.PageSize).Take(ucPager1.PageSize);
                dataGridView1.DataSource = query.ToList();

                dataGridView1.Columns["ProductCategoryId"].HeaderText = "编号";
                dataGridView1.Columns["ProductCategoryName"].HeaderText = "产品类型名称";
                return totalCount;
            }
        }

        public override void ShowAddForm()
        {
            ProductionCategoryAddEdit frm = new ProductionCategoryAddEdit(0);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ucPager1.CurrentPage = 1;
                ucPager1.GetPagerData();
            }
        }

        public override string GetFileName()
        {
            return $"产品类型表_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
        }
        public override string GetTableName()
        {
            return "ProductCategoryies";
        }

        public override void Operate(DataGridViewCellMouseEventArgs e, Point curPosition, RectangleF rectDisable, RectangleF rectEnable, RectangleF rectModify, RectangleF rectDetail, RectangleF rectReserve1, RectangleF rectReserve2)
        {
            int primaryKey = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["ProductCategoryId"].Value);
            using (var mtx = new MyContext())
            {
                var model = mtx.ProductCategories.Find(primaryKey);
                if (rectDisable.Contains(curPosition))
                {
                    if (model != null)
                    {
                        if (model.Status == 1)
                        {
                            MessageBox.Show($"该数据已禁用，不必再次禁用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        DialogResult dr = MessageBox.Show($"你确定要禁用【编号】为={primaryKey}的数据吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                        if (dr == DialogResult.Yes)
                        {
                            model.Status = 1;
                            model.LastUpdateTime = DateTime.Now;
                            model.LastUpdateUserId = LoginInfo.Id;
                            mtx.Entry(model).State = EntityState.Modified;
                            mtx.SaveChanges();
                            ucPager1.GetPagerData();
                        }
                    }
                }

                if (rectEnable.Contains(curPosition))
                {
                    if (model != null)
                    {
                        if (model.Status == 0)
                        {
                            MessageBox.Show($"该数据已启用，不必再次启用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        DialogResult dr = MessageBox.Show($"你确定要启用[编号]={primaryKey}的数据吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            model.Status = 0;
                            model.LastUpdateUserId = LoginInfo.Id;
                            model.LastUpdateTime = DateTime.Now;
                            mtx.Entry(model).State = EntityState.Modified;
                            mtx.SaveChanges();
                            ucPager1.GetPagerData();
                        }
                    }



                }

                if (rectModify.Contains(curPosition))
                {
                    if (model != null)
                    {
                        if (model.Status == 1)
                        {
                            MessageBox.Show($"该数据已禁用，不能编辑", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        ProductionCategoryAddEdit frm = new ProductionCategoryAddEdit(primaryKey);
                        if (frm.ShowDialog() == DialogResult.OK)
                            ucPager1.GetPagerData();
                    }

                }

                if (rectDetail.Contains(curPosition))
                {
                    if (model != null)
                    {
                        ProductionCategoryDetail pcd = new ProductionCategoryDetail(primaryKey);
                        pcd.ShowDialog();
                    }
                }
            }

        }
    }
}
